package zzxkj.blog.schedules;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import zzxkj.blog.dao.BlogDao;
import zzxkj.blog.dto.BlogRankInfo;
import zzxkj.blog.utils.RedisUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时同步浏览量
 * Redis->Mysql
 * @author zzxkj
 */
@Slf4j
@Component
public class ViewCountSyncTask {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BlogDao blogDao;
    /**
    *每分钟同步
    * */
//    @Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "0/20 * * * * ?")
    public void blogViewCountSync(){
        //获取前缀为:rank:blog:的key，后缀必须加上*
        Set<String> keys = redisTemplate.keys("rank:blog:*");
        //获取文章id集合
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if(redisUtil.hHasKey(key, "views")){
                ids.add(key.substring("rank:blog:".length()));
            }
        }
        if(ids.isEmpty()) {
            return;
        }
        // 需要更新阅读量
        List<BlogRankInfo> posts = blogDao.getListInIds(ids);
        if (posts.isEmpty()) {
            return;
        }
        posts.stream().forEach(blogRankInfo ->{
            Integer viewCount = (Integer) redisUtil.hget("rank:blog:" + blogRankInfo.getId(), "views");
            blogRankInfo.setViews(viewCount);
        });
        // 批量更新数据库内容
        log.info("posts:{}", posts.toString());
        Integer result = blogDao.batchIncreaseView(posts);
        //更新成功
        if(result > 0){
            log.info("ids{}, 浏览量同步成功！", ids.toString());
        }
    }
}
